
const cacheStore = new Map();
export function cache(prefix = '', ttl = 60) {
  return function (target, propertyKey, descriptor) {
    const originalMethod = descriptor.value

    descriptor.value = function (...args) {
      const key = `${prefix}`
      const now = Date.now()

      // 检查缓存是否存在且未过期
      if (cacheStore.has(key)) {
        const cached = cacheStore.get(key)
        if (now < cached.expiry) {
          return cached.data
        } else {
          // 缓存过期，删除
          cacheStore.delete(key)
        }
      }

      // 调用原始方法并缓存结果
      const result = originalMethod.apply(this, args)
      cacheStore.set(key, {
        data: result,
        expiry: now + ttl * 1000
      })
      return result
    }

    return descriptor
  }
}

export function clearCache(prefix = '') {
  return function (target, propertyKey, descriptor) {
    const originalMethod = descriptor.value
    
    descriptor.value = function (...args) {
      const result = originalMethod.apply(this, args)

      // 清除缓存
      const key = `${prefix}`
      cacheStore.delete(key)

      return result
    }

    return descriptor
  }
}

// LocalStorage 缓存装饰器
function cacheLocalStorage(ttl = 300) {
  return function (target, propertyKey, descriptor) {
    const originalMethod = descriptor.value

    descriptor.value = function (...args) {
      const key = `cache_${target.constructor.name}_${propertyKey}_${JSON.stringify(args)}`
      const now = Date.now()

      // 尝试从LocalStorage获取缓存
      const cachedStr = localStorage.getItem(key)
      if (cachedStr) {
        try {
          const cached = JSON.parse(cachedStr)
          if (now < cached.expiry) {
            console.log(`从LocalStorage缓存获取: ${propertyKey}`)
            return cached.data
          }
        } catch (e) {
          console.warn('缓存解析失败', e)
        }
      }

      // 调用原始方法并缓存结果
      const result = originalMethod.apply(this, args)

      try {
        localStorage.setKey(
          key,
          JSON.stringify({
            data: result,
            expiry: now + ttl * 1000
          })
        )
        console.log(`LocalStorage缓存设置: ${propertyKey}`, `有效期: ${ttl}秒`)
      } catch (e) {
        console.warn('LocalStorage缓存设置失败', e)
      }

      return result
    }

    return descriptor
  }
}
